package com.cq.androidtools.jsoup

import android.annotation.SuppressLint
import android.util.Log
import com.cq.androidtools.R
import com.cq.androidtools.databinding.ActivityJsoupBinding
import com.cq.androidtools.jetpack.databinding.DataBindingActivity
import org.jsoup.Jsoup
import java.io.BufferedReader
import java.io.InputStreamReader
import java.nio.charset.Charset

/**
 * 作者: CQ
 * 日期: 2022-03-09
 * 说明:
 */
class JsoupActivity : DataBindingActivity<ActivityJsoupBinding>() {
    @SuppressLint("ResourceType")
    override fun ActivityJsoupBinding.initBinding() {
        val ss = resources.openRawResource(R.raw.print)
        val sb = StringBuilder()
        var line : String? = ""
        val br = BufferedReader(InputStreamReader(ss, Charset.forName("GBK")))
        while (true) {
            line = br.readLine()
            if (line == null)
                break
//            Log.e("-----", line)
            sb.append(line)
        }
        val doc = Jsoup.parse(sb.toString())
        val links = doc.select("layout").asReversed()
        println(doc.data())
        links.forEach { it ->
            val layout = Layout()
            val attrs = TextBean()

            layout.width = it.attr("width")
            layout.height = it.attr("height")
            layout.left = it.attr("left")
            layout.top = it.attr("top")
            val text = it.select("text").first()
            attrs.type = when {
                it.`is`("text") -> {
                    "text"
                }
                it.`is`("barcode") -> {
                    "barcode"
                }
                it.`is`("table") -> {
                    "table"
                }
                else -> {
                    "text"
                }
            }
            val type = text.attr("style")
            type.split(";").forEach { value ->
                when {
                    value.startsWith("fontFamily") -> {
                        attrs.fontFamily = value.split(":")[1]
                    }
                    value.startsWith("fontSize") -> {
                        attrs.fontSize = value.split(":")[1]
                    }
                    value.startsWith("align") -> {
                        attrs.align = value.split(":")[1]
                    }
                    value.startsWith("valign") -> {
                        attrs.valign = value.split(":")[1]
                    }
                    value.startsWith("fontWeight") -> {
                        attrs.fontWeight = value.split(":")[1]
                    }
                }
            }
            attrs.body = it.text()
            layout.attrs = attrs
            Log.e("-------------------", layout.toString())
        }

    }
}